package com.hw.one.collect.config;

import java.io.BufferedReader;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import com.hw.one.collect.util.DateUtil;

/**
 * 掉线补漏
 * 
 * @auther : 王振
 * @createtime:2018/11/14 11:09
 */
public class DropTimeConfig {
//    private static String dropTimeConf = "E:/wz/data/droptime.txt";
	private static String dropTimeConf = ConditionConfig.get("dropTimeConf", ConditionConfig.collectCommon);

	public static final String modbusTime = "modbus";

	public static final String ionSoupTime = "ionsoup";

	public static final String ocecTime = "ocec";

	public static final String separator = ":";

	public static String getDropTime(String key) {
		File filename = new File(dropTimeConf);
		InputStreamReader reader = null;
		try {
			reader = new InputStreamReader(new FileInputStream(filename));
			BufferedReader br = new BufferedReader(reader);
			String line = "";
			String[] code = new String[2];
			while (null != (line = br.readLine())) {
				code = line.split(":");
				if (code[0].equals(key)) {
					return code[1];
				}
			}
			reader.close();
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 替换为最近成功的时间
	 * 
	 * @param key
	 */
	public static void putDropTime(String key) {
		// "__"替换为":"
		key = key.replaceFirst("__", ":");
		String[] faultSplit = key.split(separator);

		// 读取文件
		File file = new File(dropTimeConf);

		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
			// 内存流
			CharArrayWriter caw = new CharArrayWriter();
			// 替换
			String line = null;
			// 以行为单位进行遍历
			while ((line = br.readLine()) != null) {
				// 替换每一行中符合被替换字符条件的字符串
				if (line.contains(faultSplit[0])) {
					line = key;
				}
				// 将该行写入内存
				caw.write(line);
				// 添加换行符，并进入下次循环
				caw.append(System.getProperty("line.separator"));
			}
			// 关闭输入流
			br.close();

			// 将内存中的流写入源文件
			FileWriter fw = new FileWriter(file);
			caw.writeTo(fw);

			fw.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 根据key值获取时间
	public static LocalDateTime getDateByKey(String key) {
		if (null != key) {
			String[] faultSplit = key.split("__");
			String yyyymmddhh = faultSplit[1];
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DateUtil.NO_SPLIT_SDF_YMDH);

			LocalDateTime dateTime = LocalDateTime.parse(yyyymmddhh, formatter);
			return dateTime;
		} else {
			return null;
		}
	}
}
